package com.sgj.singleton.type7;


/**
 * 单例模式
 * 静态内部类(推荐使用)
 * @Author: Guoji Shen
 * @Date: 2021/11/11 13:58
 */
public class SingletonTest07 {
    public static void main(String[] args) {
        // 测试
        Singleton instance = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println(instance == instance2);
        System.out.println("instance.hashCode = " + instance.hashCode());
        System.out.println("instance2.hashCode = " + instance2.hashCode());
    }
}

class Singleton {
    private static volatile Singleton instance;

    private Singleton() {

    }

    // 写一个静态内部类,该类中有一个静态属性 Singleton
    // 此处利用了 jvm 底层提供的类的装在机制，保证了线程的安全
    private static class SingletonInstance {
        private static final Singleton INSTANCE = new Singleton();
    }

    // 提供一个静态的公有方法，直接返回 SingletonInstance.INSTANCE
    public static Singleton getInstance() {
        return SingletonInstance.INSTANCE;
    }
}